<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
include('update.php');
/*
 * Trieda na spravu admin fukncii systemu
 */

class Admin extends CI_Controller {

    function __construct() {
        parent::__construct();
        if (!isAdmin())
            redirect("login");
        $this->load->model('admin_model');
        $this->load->model('user_model');
        $this->load->library('form_validation');
    }

    /*
     * Index vykresli zakladny admin interface
     */

    function index() {
        $this->template->set('title', 'SKAP - admin panel');
        $this->template->view("admin_view");
    }

    /*
     * Metoda na pridanie pouzivatela
     * Metoda overy vstupy, ak su vyhovujuce zavola prislusny model
     * ak nie, vypise chybove hlasenia
     */

    function adduser() {
        $this->form_validation->set_rules('user_meno', 'meno', 'trim|required|xss_clean');
        $this->form_validation->set_rules('user_priez', 'priezvisko', 'trim|required|xss_clean');
        $this->form_validation->set_rules('user_dep', 'oddelenie', 'trim|required|xss_clean');
        $this->form_validation->set_rules('nick', 'username', 'trim|required|xss_clean');
        $this->form_validation->set_rules('pass', 'heslo', 'trim|required|xss_clean|min_length[4]');
        $this->form_validation->set_rules('pass2', 'heslo2', 'trim|required|xss_clean|matches[pass]');

        $data = array(
            'user_types' => $this->admin_model->getUserTypes(),
        );

        if ($this->form_validation->run()) {
            $input_data = array(
                'user_info' => array('first_name' => $_POST['user_meno'], 'surname' => $_POST['user_priez'], 'department' => $_POST['user_dep'], 'user_type' => $_POST['typ']),
                'user_login' => array('username' => $_POST['nick'], 'password' => sha1($_POST['pass']), 'isAdmin' => 0)
            );

            if ($this->admin_model->addUser($input_data))
                $data['mess'] = "Používateľ bol úspešne pridaný!";
            else
                $data['mess'] = "Nepodarilo sa pridať používateľa do databázy! Zrejme ide o duplicitný username.";

            $this->template->set('title', 'SKAP - admin');
            $this->template->view("admin_view", $data);
        } else {
            $this->template->set('title', 'SKAP - pridaj používateľa');
            $this->template->view("adduser_form", $data);
        }
    }

    /*
     * Metoda urcena na editaciu pouzivatelov, vytiahne vsetky udaje 
     * o pouzivatelov z Db(pomocou modelu) a vypise ich do tepmpletu 
     */

    function getuser() {

        $data = array(
            'users' => $this->admin_model->getUsers(''),
            'user_types' => $this->admin_model->getUserTypes(),
            'user_data' => isset($_POST['user']) ? $this->admin_model->getUsers(array('user_id' => array($_POST['user']))) : ""
        );
        if (isset($_POST['user']))
            redirect(base_url() . "admin/edituser/" . $_POST['user']);
        else {
            $this->template->set('title', 'SKAP - edituj používateľa');
            $this->template->view("edit_user_form", $data);
        }
    }

    /**
     * Metoda na editaciu 1 konkretneho pouzivatela
     * @param type $post - id konkretneho usera ktoreho chceme editovat
     */
    function edituser($post) {
        if (!isset($post) || !is_numeric($post) || !$this->admin_model->getUsers(array('user_id' => array($post))))
            redirect('admin');

        $this->form_validation->set_rules('user_meno', 'meno', 'trim|required|xss_clean');
        $this->form_validation->set_rules('user_priez', 'priezvisko', 'trim|required|xss_clean');
        $this->form_validation->set_rules('user_dep', 'oddelenie', 'trim|required|xss_clean');
        $this->form_validation->set_rules('nick', 'username', 'trim|required|xss_clean');
        $this->form_validation->set_rules('pass', 'heslo', 'trim|required|xss_clean|min_length[4]');
        $this->form_validation->set_rules('pass2', 'heslo2', 'trim|required|xss_clean|matches[pass]');

        $data = array(
            'users' => $this->admin_model->getUsers(''),
            'user_types' => $this->admin_model->getUserTypes(),
            'user_data' => $this->admin_model->getUsers(array('user_id' => array($post))),
            'post' => $post
        );

        if ($this->form_validation->run()) {
            $input_data = array(
                'user_id' => $post,
                'user_info' => array('first_name' => $_POST['user_meno'], 'surname' => $_POST['user_priez'], 'department' => $_POST['user_dep'], 'user_type' => $_POST['typ']),
                'user_login' => array('username' => $_POST['nick'], 'password' => sha1($_POST['pass']), 'isAdmin' => 0)
            );

            if ($this->admin_model->editUser($input_data))
                $data['mess'] = "Používateľ bol úspešne upravený!";
            else
                $data['mess'] = "Nepodarilo sa vykonať editáciu databázy! Zrejme ide o duplicitný username.";

            $this->template->set('title', 'SKAP - admin');
            $this->template->view("admin_view", $data);
        } else {
            $this->template->set('title', 'SKAP - edituj používateľa');
            $this->template->view("edit_user_form", $data);
        }
    }

    /*
     * Metoda vykresli interface pre mazanie pouzivatelov, 
     * vyberie pomocou modelu pouzivatelov z Db a vykresli do templetu
     * 
     */

    function deleteuser() {
        $data = array(
            'users' => $this->admin_model->getUsers(''),
            'user_data' => isset($_POST['user']) ? $this->admin_model->getUsers(array('user_id' => array($_POST['user']))) : ""
        );
        if (isset($_POST['user']))
            $this->delete($_POST['user']);
        else {
            $this->template->set('title', 'SKAP - vymaž používateľa');
            $this->template->view("deleteuser_form", $data);
        }
    }

    /*
     * Metoda na mazanie konkretneho pouzivatela
     * @param type $id - id pouyivatela ktory sa ma zmazat
     */

    function delete($id) {
        $data_del['user_id'] = $id;

        if ($this->admin_model->deleteUser($data_del))
            $data['mess'] = "Používateľ bol úspešne odstránený";
        else
            $data['mess'] = "Používateľ NEbol úspešne odstránený";

        $data['users'] = $this->admin_model->getUsers('');

        $this->template->set('title', 'SKAP - vymaž používateľa');
        $this->template->view("deleteuser_form", $data);
    }

    /*
     *  Metoda urcena na editaciu eventov, vytiahne z db eventy
     *  a vypise ich do dropboxu, kde je mozno zvolit event ktory 
     *  chceme editovat
     */

    function editevent() {
        if (isset($_POST['user']) || isset($_POST['type']) || isset($_POST['room'])) {
            if (isset($_POST['user']))
                $conds['users'] = array(0 => $_POST['user']);
            if (isset($_POST['type']))
                $conds['event_type'] = array(0 => $_POST['type']);
            if (isset($_POST['room']))
                $conds['room_id'] = array(0 => $_POST['room']);
        }

        $data = array(
            'users' => $this->admin_model->getUsers(''),
            'types' => $this->user_model->getEventTypes(),
            'rooms' => $this->user_model->getRooms(),
            'events' => isset($conds) ? $this->user_model->getEvents($conds) : ""
        );
        $this->template->set('title', 'SKAP - edtitácia eventu');
        $this->template->view("edit_event_form", $data);
    }

    /*
     * Metoda na editaciu konkretneho eventu
     * @param type $id - id eventu ktory chceme editovat
     */

    function edit($id = "") {
        if (!isset($id))
            redirect('admin');
        $this->form_validation->set_rules('event_meno', 'meno', 'trim|required|xss_clean');

        $event = $this->user_model->getEvents(array('event_id' => array(0 => $id)));

        $od_time = explode(':', getStringTimeFromMinutes($event[0]["start_time"]));
        $do_time = explode(':', getStringTimeFromMinutes($event[0]["end_time"]));
        $date = explode('-', $event[0]['event_day']);

        $val = array(
            'event_meno' => $event[0]["description"],
            'typ' => $event[0]["event_type"],
            'room' => $event[0]["room_id"],
            'od_hod' => $od_time[0],
            'od_min' => $od_time[1],
            'do_hod' => $do_time[0],
            'do_min' => $do_time[1],
            'datum' => isset($date[0]) ? $date[0] : "",
            'mesiac' => isset($date[1]) ? $date[1] : "",
            'rok' => isset($date[2]) ? $date[2] : "",
            'den' => $event[0]['event_day']
        );

        $data['val'] = $val;
        $data['types'] = $this->user_model->getEventTypes();
        $data['rooms'] = $this->user_model->getRooms();
        $data['id'] = $id;


        if ($this->form_validation->run()) {
            $date = "";
            switch ($_POST["typ"]) {
                case 1: $date = $_POST["den"];
                    break;
                case 2:;
                case 3: $date = $_POST["datum"] . "-" . $_POST["mesiac"] . "-" . $_POST["rok"];
            };
            $input = array(
                'event_id' => $id,
                'event' => array(
                    'description' => $_POST["event_meno"],
                    'event_type' => $_POST["typ"],
                    'event_day' => $date,
                    'start_time' => ($_POST["od_hod"] * 60) + $_POST["od_min"],
                    'end_time' => ($_POST["do_hod"] * 60) + $_POST["do_min"],
                    'room_id' => $_POST['room'])
            );

            if ($input['event']['end_time'] - $input['event']['start_time'] <= 0) {
                $data['mess'] = "Zadali ste nesprávne trvanie eventu";
                $this->template->set('title', 'SKaP - editovať udalosť');
                $this->template->view("edit_event_admin", $data);
                return;
            }
            if ($this->user_model->editEvent($input))
                $data['mess'] = "Event bol úspešne aktualizovaný!";
            else
                $data['mess'] = "Event NEbol úspešne aktualizovaný! Skuste ho pridať aktualizovať, alebo kontaktujte admina.";
            redirect('admin/editevent');
        } else {
            $this->template->set('title', 'SKaP - editovať udalosť');
            $this->template->view("edit_event_admin", $data);
        }
    }

    /*
     * Metoda urcena na mazanie eventu podla id
     * @param type $id - id eventu ktory sa ma zmazat
     * 
     */

    function deleteevent($id) {
        if (!isset($id) || $id == "")
            redirect('admin');
        $data = array(
            'users' => $this->admin_model->getUsers(''),
            'types' => $this->user_model->getEventTypes(),
            'rooms' => $this->user_model->getRooms(),
            'events' => isset($conds) ? $this->user_model->getEvents($conds) : ""
        );
        $input['event_id'] = $id;
        var_dump($input);
        if ($this->admin_model->deleteEvents($input))
            $data['mess'] = "Event bol úspešne odstránený";
        else
            $data['mess'] = "Event NEbol úspešne odstránený";



        $this->template->set('title', 'SKAP - vymaž edituj event');
        $this->template->view("edit_event_form", $data);
    }

    /**
     * Metoda sluziaca na hromadny import rozvrhov z xml, 
     * metoda sluzi iba na vykreslenie interfaceu, update prebieha v 
     * update triede.
     * @return type 
     */
    function update() {

        if (isset($_POST['submit'])) {
            if ($meta = $this->do_upload_xml()) {
                $export = new Update();
                if ($export->updateData($meta['file_name']))
                    $data['mess'] = "Update databázy prebehol úspešne!";
                else
                    $data['mess'] = "Update databázy NEprebehol úspešne!";

                $this->template->set('title', 'SKAP - Update rozvrhov');
                $this->template->view("upload_form", $data);
                return;
            } else {
                $data['mess'] = "Nepodarilo sa nahrať xml súbor";
                $this->template->set('title', 'SKAP - Update rozvrhov');
                $this->template->view("upload_form", $data);
            }
        } else {

            $this->template->set('title', 'SKAP - Update rozvrhov');
            $this->template->view("upload_form");
        }
    }

    /**
     * metoda sluziaca na upload xml suboru na server.
     * @return boolean 
     */
    function do_upload_xml() {
        $config['upload_path'] = 'temp';
        $config['allowed_types'] = 'xml';


        $this->load->library('upload', $config);
        if (!$this->upload->do_upload())
            return false;
        else
            return $this->upload->data();
    }

    /**
     * Metóda zobrazí používateľskú príručku
     */
    function help() {
        $this->template->set('title', 'SKAP - používateľská príručka');
        $this->template->view('admin_help_view');
    }

}

?>